package com.itheima.controller;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


@RequestMapping("/uploadController")
@RestController
public class UploadController {
    @RequestMapping("/upload")
    public void upload(MultipartFile[] files, HttpServletRequest req) throws IOException {

        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                String realPath = req.getServletContext().getRealPath("/upload");
                //2 生成唯一的文件名
                //2.1 获取到原始文件名
                String filename = file.getOriginalFilename();
                //2.2 生成唯一UUID
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                //2.3 获取文件的后缀名
                String s = filename.substring(filename.lastIndexOf("."));
                //2.4 组合成新的文件名
                filename = uuid + s;
                //3 保存到目录中
                file.transferTo(new File(realPath,filename));
            }
        }
    }
}
